package com.talkyoung.ptbpro.controller;

import com.talkyoung.ptbcommon.CommonResult;
import com.talkyoung.ptbpojo.entity.User;
import com.talkyoung.ptbpojo.entity.UserStatistics;
import com.talkyoung.ptbpro.service.UserService;
import com.talkyoung.ptbpro.common.util.EcodeUtil;
import com.talkyoung.ptbpro.service.UserStatisticsService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@RequestMapping("/register")
@RestController
public class RegisterController {

    private static Logger logger = LoggerFactory.getLogger(RegisterController.class);

    private static String dateFormate = "yyyy-MM-dd HH:mm:ss";

    @Autowired
    UserService userService;

    @Autowired
    UserStatisticsService userStatisticsService;

    @RequestMapping(method = RequestMethod.POST)
    public CommonResult<String> register(@RequestBody User user){
        //缺省设置
        user.setStatus(1);
        user.setCreateTime(new SimpleDateFormat(dateFormate).format(new Date()).toString());
        if(StringUtils.isNotBlank(user.getPassword())){
            user.setPassword(EcodeUtil.encodePwd(user.getPassword()));
        }
        try{
            userService.insert(user);
            UserStatistics userStatistics = new UserStatistics();
            userStatistics.setUserId(user.getId());
            userStatisticsService.insert(userStatistics);
            return CommonResult.success("Register success.");
        }catch (Exception e){
            logger.error("Register failed：",e);
            return CommonResult.failed("Register failed.");
        }
    }
}
